<template>
  <div>
    <div id="map"></div>
    <div class="tip">
      <div class="ss-box">
        <input
          type="text"
          id="keyword"
          class="keyword"
          name="keyword"
          v-model="keyword"
          placeholder="输入关键词搜索"
          @keyup="keywordKeyup"
        />
        <a
          v-if="keyword && keyword.length > 0"
          href="javascript:void(0);"
          title="关闭"
          class="ss-xx"
          @click="closeSearch"
        ></a>
        <button type="button" id="btnSearch" title="搜索" @click="search">
          <span></span>
        </button>
      </div>
      <div
        class="jiansuo"
        id="searchSuggest"
        v-if="searchResult && searchResult.length > 0"
      >
        <ul id="suggestList">
          <li
            v-for="(val, key, index) in searchResult"
            :key="index"
            :data-lng="val.lng"
            :data-lat="val.lat"
            @click="resultClick(val)"
          >
            {{ val.name }}
          </li>
        </ul>
      </div>
    </div>
    <div class="calculation-box">
      <p>
        已绘制的图形面积：<strong class="area">{{ calcArea }}</strong> m²
      </p>
    </div>
    <!-- 搜索宗地详情 -->
    <div class="parcel-detail" v-if="parcelDetail">
      <img
        src="../images/close.svg"
        class="close"
        title="关闭"
        @click="closeParcelDetail"
      />
      <ul>
        <li>
          <span style="margin-right: 10px"
            ><span>宗地号：</span
            ><span name="parcelNo">{{
              parcelDetail.attributes.xtBusinessType.parcelNo
            }}</span></span
          >
          <a
            href="javascript:void(0);"
            @click="insertParcel(parcelDetail.location)"
            >[插入宗地图形]</a
          >
        </li>
        <li>
          <span style="margin-right: 10px"
            ><span>宗地代码：</span
            ><span name="parcelCode">{{
              parcelDetail.attributes.xtBusinessType.parcelCode
            }}</span></span
          >
        </li>
        <li>
          <span style="margin-right: 10px"
            ><span>面积：</span
            ><span name="luArea">{{
              parcelDetail.attributes.xtBusinessType.luArea
            }}</span></span
          >
        </li>
        <li>
          <span>单位：</span
          ><span name="unit">{{
            parcelDetail.attributes.xtBusinessType.unit
          }}</span>
        </li>
        <li>
          <span>所属区域：</span><span name="quName"></span
          ><span name="jdName"
            >{{ parcelDetail.attributes.xtBusinessType.quName
            }}{{ parcelDetail.attributes.xtBusinessType.jdName }}</span
          >
        </li>
        <li>
          <span>宗地地址：</span
          ><span name="luLocation">{{
            parcelDetail.attributes.xtBusinessType.luLocation
          }}</span>
        </li>
        <li>
          <span>登记状态：</span
          ><span name="estateState">{{
            parcelDetail.attributes.xtBusinessType.estateState
          }}</span>
        </li>
      </ul>
    </div>
    <!-- 全量宗地详情 -->
    <div class="parcel-detail" v-if="parcelDetail2">
      <img
        src="../images/close.svg"
        class="close"
        title="关闭"
        @click="closeParcelDetail2"
      />
      <ul>
        <li>
          <span style="margin-right: 10px"
            ><span>宗地号：</span
            ><span name="parcelNo">{{ parcelDetail2.parcelNo }}</span></span
          >
          <a
            href="javascript:void(0);"
            @click="insertParcel(parcelDetail2.location)"
            >[插入宗地图形]</a
          >
        </li>
        <li>
          <span style="margin-right: 10px"
            ><span>宗地代码：</span
            ><span name="parcelCode">{{ parcelDetail2.lotNo }}</span></span
          >
        </li>
        <li>
          <span style="margin-right: 10px"
            ><span>面积：</span
            ><span name="luArea">{{ parcelDetail2.shapeArea }}</span></span
          >
        </li>
        <li>
          <span>单位：</span><span name="unit">{{ parcelDetail2.unit }}</span>
        </li>
        <li>
          <span>街道：</span
          ><span name="luLocation">{{ parcelDetail2.jdmc }}</span>
        </li>
        <li>
          <span>登记状态：</span
          ><span name="estateState">{{ parcelDetail2.estateState }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import "mapbox-gl/dist/mapbox-gl.css";
import "@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css";
import "@/css/index.css";
import "@/css/search.css";
import Index from "@/js/index";
import * as turf from "@turf/turf";
import mapboxgl from "mapbox-gl";
import request from "@/utils/request";
export default {
  data() {
    return {
      map: null,
      calcArea: null,
      keyword: "",
      marker: new mapboxgl.Marker(),
      villageId: "c76e1d15-4c39-471b-a2e6-6dffbd4bcdae",
      initGeom: null,
      searchResult: [],
      parcelDetail: null,
      parcelDetail2: null,
    };
  },
  methods: {
    drawUpdate(area) {
      this.calcArea = area;
    },
    insertParcel(geoJson) {
      if (geoJson) {
        Index.drawGeometry(JSON.parse(geoJson));
      }
    },
    getVillageGeom() {
      //TODO 这里调接口getGeomById获取物业区域已有落图
      var resData = {
        data: {
          villageId: "1044030501010305",
          // "geom":"{\"coordinates\":[[[[113.83607487113574,22.572042389082327],[113.83965166146675,22.57157374778778],[113.83870912887954,22.569699166677168],[113.8351081710465,22.570011598632817],[113.83607487113574,22.572042389082327]]],[[[113.83293309584457,22.572801138275196],[113.83573652610414,22.572466396498825],[113.83484232852106,22.570234763881388],[113.83281225833423,22.570435612296293],[113.83293309584457,22.572801138275196]]]],\"type\":\"MultiPolygon\"}",
          geom: '{"type":"MultiPolygon","coordinates":[[[[[113.85743111572305,22.583920820466133],[113.8597056289679,22.582276393445824],[113.8590618988041,22.58187023676126],[113.85669082603437,22.58333635768919],[113.85743111572305,22.583920820466133]]],[[[113.85628332328605,22.582959662158757],[113.85647919983717,22.582665122303638],[113.85581881603673,22.581952023205133],[113.85529834406037,22.582076040704877],[113.85628332328605,22.582959662158757]]]],[[[113.85980344869199,22.58200799383124],[113.86064256798556,22.581274529002016],[113.86052509128575,22.58102659634561],[113.85935032427392,22.58162060092222],[113.85980344869199,22.58200799383124]]]]}',
          createTime: "2021-11-04T12:14:41",
          updateTime: "2021-11-04T14:09:43",
          type: 2,
          deleted: false,
        },
        msg: "success",
        success: true,
        status: 200,
        errorMsg: null,
      };
      if (resData.success && resData.data && resData.data.geom) {
        this.initGeom = JSON.parse(resData.data.geom);
        Index.setInitGeometry(this.initGeom);
        Index.drawGeometry(this.initGeom);
      }
    },
    keywordKeyup(e) {
      if (e.keyCode == 13) {
        this.search();
      }
    },
    search() {
      let keyword = this.keyword;
      if (keyword.length == 0) {
        return;
      }
      //TODO 此处请改为调用搜索接口search
      var serachResult = {
        status: 0,
        success: true,
        data: {
          parcelModel: {
            id: 1589857,
            basicId: "A816-0060",
            type: "parcel",
            name: "1440306406003GB00154DST1100021095",
            location:
              '{"type":"Polygon","coordinates":[[[114.00923034866479,22.641596001577305],[114.00861806359485,22.64121812372688],[114.00855009249746,22.641178757324703],[114.00847981602683,22.64114305729298],[114.00840742487293,22.641111297235007],[114.00833321087856,22.641083392248543],[114.00800804938567,22.640971416679804],[114.00792571604607,22.640940583402532],[114.00784541183495,22.64090526646917],[114.00776751910051,22.640865743092583],[114.007692135137,22.64082210538001],[114.00754185445008,22.640729417098594],[114.00740798627595,22.640755210094497],[114.00732964651638,22.640867499318546],[114.00724559777218,22.641031178052913],[114.00733962564601,22.641082155804312],[114.00707024267751,22.64149958353223],[114.00693435431256,22.641433855641438],[114.00667425601722,22.641806451660475],[114.00671742841308,22.641993725283367],[114.00697476831293,22.64214852600736],[114.00707726021855,22.64221020437024],[114.00724548188433,22.642290260761733],[114.00751640707593,22.64243118593709],[114.00831903686228,22.64291385860402],[114.00842001313481,22.642893776404318],[114.0090666565167,22.64196452325149],[114.00913520760251,22.641865987709963],[114.00925292640528,22.641696698284296],[114.00923034866479,22.641596001577305]]]}',
            attributes: {
              xtBusinessType: {
                estateState: "登记发证",
                jdCode: null,
                jdName: "民治街道",
                lamStage: "A",
                luArea: 35673.14,
                luFunction: "二类居住用地,商业用地",
                luLocation: "龙华新区民治街道腾龙路与建设路交汇处",
                parLotNo: "5000472640",
                parcelCode: "440306406003GB00154",
                parcelNo: "A816-0060",
                quCode: null,
                quName: "龙华区",
                statusEstate: 1,
                unit: "深圳悦茂置业有限公司",
              },
            },
          },
          villageList: [
            {
              id: "1378",
              name: "中台电热（深圳）有限公司工业区",
              sectionId: "5e676a25-abc1-4574-a7eb-208e5f406f18",
              streetId: "1d89ba17-87f6-4982-a655-7ddf3a8e20dd",
              geom: '{"type":"Polygon","coordinates":[[[113.867113506,22.811248425],[113.867656597,22.810562294],[113.869805559,22.811845212],[113.869177337,22.812719221],[113.867113506,22.811248425]]]}',
            },
            {
              id: "1176",
              name: "中国高科深圳工业园",
              sectionId: "0c75cbab-731a-4140-ba93-ca781dc07331",
              streetId: "20",
              geom: '{"type":"Polygon","coordinates":[[[113.894244942,22.51002177],[113.893380178,22.51046264],[113.892923832,22.509555582],[113.893826648,22.509099733],[113.894244942,22.51002177]]]}',
            },
            {
              id: "1683",
              name: "中建二局深圳南方实业平湖厂区",
              sectionId: "80288a5a-66d4-4984-bd13-a190be0e56b0",
              streetId: "39",
              geom: '{"type":"Polygon","coordinates":[[[114.113312057,22.70027334],[114.113346069,22.700924201],[114.114291605,22.70089501],[114.114248576,22.700252138],[114.113312057,22.70027334]]]}',
            },
            {
              id: "1496",
              name: "再兴电子（深圳）有限公司松岗洋涌工业园",
              sectionId: "5e676a25-abc1-4574-a7eb-208e5f406f18",
              streetId: "1d89ba17-87f6-4982-a655-7ddf3a8e20dd",
              geom: '{"type":"Polygon","coordinates":[[[113.824728152,22.798449742],[113.82585819,22.798575832],[113.826934084,22.798636839],[113.8269663,22.796624597],[113.825885389,22.796617561],[113.825874329,22.797087378],[113.824755313,22.797095262],[113.824728152,22.798449742]]]}',
            },
          ],
          buildingList: [
            {
              id: "72078551",
              name: "深圳卷烟厂易地技术改造工程片烟库C",
              sectionId: "0b161242-a954-458d-86aa-9222a8348b66",
              streetId: "32",
              geom: '{"type":"Polygon","coordinates":[[[114.051866267,22.680434291],[114.051784474,22.680433057],[114.051632521,22.680430737],[114.051469166,22.680428237],[114.051316605,22.680425941],[114.051234661,22.68042467],[114.051240032,22.680147707],[114.051474005,22.680151195],[114.05147455,22.680116736],[114.051476058,22.680033008],[114.051242008,22.680029518],[114.051246618,22.679752509],[114.051328791,22.679753713],[114.05148082,22.679756001],[114.051644175,22.679758428],[114.051796432,22.679760683],[114.051878223,22.679761917],[114.051873313,22.680038746],[114.051639417,22.68003526],[114.051637903,22.68011927],[114.051637356,22.680153836],[114.051871102,22.68015732],[114.051866267,22.680434291]]]}',
            },
            {
              id: "90966697",
              name: "深圳能源物流有限公司二期仓库",
              sectionId: "5ffb55c2-3e67-4515-b3df-57810e2dcc37",
              streetId: "56",
              geom: '{"type":"Polygon","coordinates":[[[114.053407598,22.505842102],[114.053401629,22.505865683],[114.053376969,22.505860414],[114.053366001,22.505857993],[114.05308137,22.505795169],[114.05304694,22.505788337],[114.053044897,22.505796438],[114.053000059,22.50578552],[114.053020895,22.50570372],[114.053022123,22.505698783],[114.053030787,22.50566466],[114.053035037,22.505647854],[114.053039614,22.505629897],[114.053078017,22.505479037],[114.053086675,22.505445259],[114.053080017,22.505443797],[114.053088515,22.50541052],[114.053090312,22.505403429],[114.053096893,22.505404881],[114.053117718,22.505323585],[114.053139233,22.505246276],[114.05353277,22.505333855],[114.053510484,22.505420316],[114.053514721,22.505421263],[114.053504015,22.505463327],[114.053496828,22.505491448],[114.053486452,22.505532114],[114.053425164,22.505773111],[114.053420183,22.505792525],[114.053407598,22.505842102]]]}',
            },
            {
              id: "187865741",
              name: "深圳市生物医药创新产业园区1栋",
              sectionId: "9e03be68-4df2-47ad-ba6b-3b2d72d3900c",
              streetId: "51",
              geom: '{"type":"Polygon","coordinates":[[[114.399991099,22.743087704],[114.401934227,22.744230677],[114.402224448,22.743814864],[114.40027629,22.742676863],[114.399991099,22.743087704]]]}',
            },
            {
              id: "3630",
              name: "深圳湾锦缎之滨服务会所",
              sectionId: "0c75cbab-731a-4140-ba93-ca781dc07331",
              streetId: "25",
              geom: '{"type":"Polygon","coordinates":[[[113.948154235,22.527812588],[113.948126739,22.527832817],[113.948098282,22.527851744],[113.948068712,22.527869311],[113.948038332,22.527885507],[113.948007066,22.527900259],[113.947975069,22.527913537],[113.947942416,22.527925323],[113.947867671,22.527946021],[113.947815417,22.527945971],[113.947815421,22.527965974],[113.947764915,22.527965934],[113.947754963,22.52796593],[113.947755125,22.527811425],[113.947765096,22.527802201],[113.947779009,22.527789267],[113.94777806,22.527787204],[113.94777719,22.527785092],[113.947776394,22.527782926],[113.947775752,22.527780748],[113.947775186,22.527778533],[113.947774772,22.527776303],[113.947774511,22.527774042],[113.947774326,22.52777178],[113.94777429,22.527769523],[113.947774333,22.527767247],[113.947774529,22.527764993],[113.947774875,22.52776274],[113.947775296,22.527760506],[113.947775868,22.527758309],[113.947776518,22.527756116],[113.947777318,22.527753977],[113.947778267,22.527751874],[113.947779218,22.527749809],[113.947780395,22.527747799],[113.947781647,22.527745843],[113.947782973,22.527743943],[113.947784375,22.527742114],[113.947785928,22.527740356],[113.947787554,22.527738654],[113.947789255,22.527737059],[113.947791107,22.52773552],[113.947792956,22.527734084],[113.947794881,22.527732723],[113.947796956,22.527731451],[113.947799027,22.527730285],[113.947801175,22.527729227],[113.947803396,22.527728256],[113.947805615,22.527727393],[113.947807983,22.527726636],[113.947810273,22.527725987],[113.947812638,22.527725441],[113.947815076,22.527725022],[113.947817513,22.527724691],[113.947819871,22.5277245],[113.947822379,22.527724399],[113.947824809,22.527724421],[113.947827237,22.527724549],[113.947829663,22.527724801],[113.947832087,22.527725156],[113.947834432,22.527725635],[113.947836776,22.527726221],[113.947839118,22.527726911],[113.947841382,22.527727706],[113.947846053,22.527729705],[113.947850492,22.527732017],[113.947851354,22.527730549],[113.947860277,22.527716422],[113.947867009,22.527705788],[113.948110805,22.527710472],[113.948197435,22.527712139],[113.94819731,22.527714694],[113.948196418,22.527754264],[113.948210236,22.52775454],[113.9482097,22.527779087],[113.948216532,22.527779215],[113.948216215,22.527792051],[113.948195566,22.527791663],[113.948154717,22.527790882],[113.948154235,22.527812588]]]}',
            },
          ],
        },
        message: "操作成功",
      };

      var data = serachResult.data;
      var searchResult = [];
      //宗地
      if (data.parcelModel) {
        let center = turf.center(JSON.parse(data.parcelModel.location)),
          lng = center.geometry.coordinates[0],
          lat = center.geometry.coordinates[1],
          parcelNo = data.parcelModel.attributes.xtBusinessType.parcelNo;
        searchResult.push({
          name: "【宗地】" + parcelNo,
          lng: lng,
          lat: lat,
          parcelModel: data.parcelModel,
          type: "parcel",
        });
      }
      if (data.villageList.length > 0) {
        data.villageList.forEach((item) => {
          let center = turf.center(JSON.parse(item.geom)),
            lng = center.geometry.coordinates[0],
            lat = center.geometry.coordinates[1];
          searchResult.push({
            name: "【物业区域】" + item.name,
            lng: lng,
            lat: lat,
            type: "village",
          });
        });
      }
      if (data.buildingList.length > 0) {
        data.buildingList.forEach((item) => {
          let center = turf.center(JSON.parse(item.geom)),
            lng = center.geometry.coordinates[0],
            lat = center.geometry.coordinates[1];
          searchResult.push({
            name: "【项目栋】" + item.name,
            lng: lng,
            lat: lat,
            type: "building",
          });
        });
      }
      var maxLength = 20;
      if (searchResult.length < maxLength) {
        //天地图
        let parameters_tianditu = {
          type: "query",
          tk: "7a753b505fb9d813474aae1a1bee2533",
          postStr: {
            keyWord: this.keyword,
            specify: "156440300",
            queryType: "12",
            start: "0",
            count: maxLength - searchResult.length,
          },
        };
        request({
          url: "https://api.tianditu.gov.cn/v2/search",
          method: "get", //请求方法
          params: parameters_tianditu,
        }).then((res) => {
          res.data.pois.forEach((item) => {
            let lng = item.lonlat.split('"')[0].split(",")[0];
            var lat = item.lonlat.split('"')[0].split(",")[1];
            searchResult.push({
              name: item.name,
              lng: lng,
              lat: lat,
              type: "tianditu",
            });
          });
        });
      }
      this.searchResult = searchResult;
    },
    save(res) {
      var geoJson;
      if (res && res.features && res.features.length > 0) {
        if (res.features.length == 1) {
          geoJson = JSON.stringify(res.features[0].geometry);
        } else {
          var coordinates = [];
          res.features.forEach((item) => {
            coordinates.push(item.geometry.coordinates);
          });
          geoJson = JSON.stringify({
            type: "MultiPolygon",
            coordinates: coordinates,
          });
        }
      }

      var paras = { id: this.villageId, geoJson: geoJson };
      console.log(paras);
      //TODO 调用接口save保存落图数据paras
    },
    // 关闭宗地详情
    closeParcelDetail() {
      this.parcelDetail = null;
      Index.addParcelLayer();
    },
    closeSearch() {
      this.searchResult = null;
      this.keyword = null;
      this.marker.remove();
    },
    resultClick(res) {
      var center = [res.lng, res.lat];
      this.marker.setLngLat(center).addTo(this.map);
      this.map.flyTo({
        center: center,
        zoom: 17,
      });
      this.parcelDetail = res.parcelModel;
      //新增，插入宗地图层
      if (this.parcelDetail && this.parcelDetail.location) {
        Index.addParcelLayer(JSON.parse(this.parcelDetail.location));
      }
    },
    // 宗地点击事件
    parcelClick(properties) {
      var objectId = properties.OBJECTID;
      request({
        url: "http://localhost:8018/api/parcel/getDetailById",
        method: "get", //请求方法
        params: { objectId: objectId },
      }).then((res) => {
        if(res.status!=200){
          return;
        }
        let data=res.data.data;
        console.log(data);
      this.parcelDetail2 = {
        ...data,
        location: data.geom,
      };
      });
    },
    // 宗地点击事件
    closeParcelDetail2() {
      this.parcelDetail2 = null;
      Index.highlightParcelLayer();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.map = Index.initMap({
        drawUpdate: this.drawUpdate,
        saveFeature: this.save,
        load: this.getVillageGeom,
        parcelClick: this.parcelClick,
      });
    });
  },
};
</script>
<style scoped>
@import url("mapbox-gl/dist/mapbox-gl.css");
</style>